import { Provide, Inject, HttpClient, Config } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
@Provide()
export class MfAthService {
  @Inject()
  ctx: Context;

  @Config('dingtalkAuthConfig')
  dingtalkAuthConfig: any;
  /**
   * 获取用户列表
   * @returns 
   */
  async getSysUserLists(data:any): Promise<any> {
    const { ctx } = this;
    const userInfo = ctx.userInfo;
    
    const _url = `${this.dingtalkAuthConfig.oauth_path}/api/v1/sysUser/list?page=${data.pageNum}&pageSize=${data.pageSize}`;
    let _data = {
      userName: data.searchKey || "",
      loginName: data.searchKey || ""
    }
    if(!userInfo.is_admin){
      _data = {
        userName: userInfo.nick,
        loginName: userInfo.nick
      }
    }
    const _headers = {
      "mfagentid": data.mfagentid,
      "mfuuid": data.mfuuid,
    };
    return await this.httpRequest("POST", _url, _data, _headers);
  }

  /**
     * 发起请求
     * @param {string} method 
     * @param {string} url 
     * @param {string} data 
     * @param {string} headers 
     * @returns 
     */
  async httpRequest(method: string, url: string, data: object = {}, headers: object = {}) {
    // eslint-disable-next-line no-useless-catch
    try {
      const httpclient = new HttpClient();
      const result = await httpclient.request(url, {
        method: method,
        data: data,
        dataType: 'json',
        contentType: 'json',   // 发送的 post 为 json
        headers: {
          'Content-Type': 'application/json',
          ...headers
        }
      });
      return {
        success: (result && result.status == 200) ? true : false,
        ...result.data.data
      }
    } catch (error) {
      throw error;
    }
  }
}